import attention from './attention.js'
import {apiUrl_config} from '@/config.js'
export const Baseurl = apiUrl_config

export const axios = (params) => {
	// 验证token
	const token = uni.getStorageSync('elybToken') || ''
	let header = {
		'Authorization': token
	}
	uni.showLoading({title: '加载中',mask: true});
	if (params.data !== undefined) {
		// 配置是否是FORMDATA模式
		if (params.data.formData) {
			header['Content-Type'] = 'application/x-www-form-urlencoded'
			delete params['data'].formData
		} else {
			if (params.method == 'get' || params.method == 'delete') {
				header['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
			} else {
				header['Content-Type'] = 'application/json'
			}
		}
	} else {
		header['Content-Type'] = 'application/json'
	}

	// 封装
	return new Promise((resolve, reject) => {
		header['Authorization'] = uni.getStorageSync('elybToken') || ''
		uni.request({
			header,
			// 对象的展开运算符
			params,
			// 重新定义url
			url: Baseurl + params.url,
			method: params.method || 'post',
			data: params.data,
			success: (result) => {
				let code = result.data.code
				if (code == 200) {
					resolve(result.data);
				} else if (code == 401) {
					attention.noIcon('登录失效，即将重新登录')
					uni.clearStorageSync()
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/index'
						})
					}, 300)
				} else if(code == 501) {
					attention.noIcon(result.data.msg)
					reject(result);
				}else{
					reject(result);
					setTimeout(() => {
						attention.noIcon(result.data.msg)
					}, 1000)
				}
				uni.hideLoading();
			},
			fail: (err) => {
				reject(err);
				uni.hideLoading();
			},
			complete: () => {
				// 关闭正在加载中的图标
				uni.hideLoading();
			}
		})
	})
}
